<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Filter Image</title>
    <script src="./js/jquery-1.11.1.min.js"></script>
    <script src="./js/jszip.min.js"></script>
    <script src="./js/FileSaver.js"></script>

    <style>
        .image-preview {
            margin-top: 20px;
            width: 100%;
        }

        .image-container {
            display: inline-block;
            margin: 10px;
        }

        .image-container img {
            width: 50px;
            height: auto;
            display: block;
        }
    </style>
</head>

<body>
    <input type="file" id="imageInput" accept="image/*">

    <button id="saveButton">保存修改后的图片</button>
    <span>
        总数：<span id="total"></span>，成功数量：<span id="successCount"></span>，失败数量：<span id="failedCount"></span>
    </span>

    <div class="image-preview" id="imagePreview"></div>

    <script>
        var saveImages = [];
        $(document).ready(function () {
            var filterList = [
                { title: '灰度', value: 'grayscale' },
                { title: '二值化滤镜', value: 'binarize' },
                { title: '浮雕滤镜', value: 'emboss' },
                { title: '亮度增强', value: 'enhanced' },
                { title: '高斯模糊滤镜', value: 'blur' },
                { title: '锐化', value: 'apply_sharpen' },
                { title: '轮廓滤镜', value: 'contour' },
                { title: '细节滤镜', value: 'detail' },
                { title: '边缘增强滤镜', value: 'edgeenhance' },
                { title: '平滑滤镜', value: 'smooth' },
                { title: '更强平滑滤镜', value: 'smoothmore' },
                { title: '美颜', value: 'bifilter' },
                { title: '怀旧滤镜', value: 'huaijiu' },
                { title: '流年滤镜', value: 'liulian' },
                { title: '光照滤镜', value: 'guangzhao' },
                { title: '凸透镜滤镜', value: 'tuTouJing' },
                { title: '素描滤镜', value: 'sumiao' },
                { title: '全彩', value: 'quancai' },
                { title: '铅笔画滤镜', value: 'qianbihua' },
                { title: '只保留边界滤镜', value: 'bianjie' },
                { title: '反色滤镜', value: 'fanse' },
                { title: '水彩画', value: 'stylization' },
                { title: '卡通滤镜', value: 'katong' },
                { title: '摄影效果滤镜', value: 'dianying' }
            ];

            $("#imageInput").on('change', function (event) {
                var files = event.target.files;
                if (files.length > 0) {
                    var imageFile = files[0];
                    let options = {
                        img_url: 'https://watermarkud.obs.cn-east-3.myhuaweicloud.com/app-mp/staticv3/canvas-filters/original.jpg',
                    }

                    const previewContainer = document.getElementById('imagePreview');
                    previewContainer.innerHTML = ''; // 清空预览区域

                    saveImages = [];

                    function photoFilter(filter) {
                        options['filter_type'] = filter.value

                        $.ajax({
                            url: '/photo_filter',
                            type: 'POST',
                            data: JSON.stringify(options),
                            contentType: "application/json",
                            success: function (response) {
                                console.log(response);

                                const resizedImg = new Image();
                                resizedImg.src = response;

                                const container = document.createElement('div');
                                container.classList.add('image-container');
                                container.appendChild(resizedImg);
                                previewContainer.appendChild(container);

                                saveImages.push({
                                    name: filter.value + '.jpg',
                                    url: resizedImg.src
                                })
                            },
                            error: function (xhr, status, error) {
                                console.error('Error applying filter: ' + filter.title, error);
                            }
                        });
                    }

                    for (let i = 0; i < filterList.length; i++) {
                        photoFilter(filterList[i])
                    }
                }
            });

            document.getElementById('saveButton').addEventListener('click', function () {
                if (saveImages.length === 0) {
                    alert('暂无图片');
                    return;
                }
                downloadAndCompressFiles(saveImages, null, (successCb, failedCb) => {
                    // document.getElementById('downloadButton').textContent = '开始下载';
                    // document.getElementById('downloadButton').disabled = false;
                    // console.log('成功数量', successCb || 0)
                    // console.log('失败数量', failedCb || 0)
                }, (progressRes) => {
                    document.getElementById('total').innerText = progressRes.total;
                    document.getElementById('successCount').innerText = progressRes.successCount;
                    document.getElementById('failedCount').innerText = progressRes.failedCount;
                })
            });

            function base64ToBlob(dataurl) {
                let arr = dataurl.split(',')
                let mime = arr[0].match(/:(.*?);/)[1]
                let bstr = atob(arr[1])
                let n = bstr.length
                let u8arr = new Uint8Array(n)
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n)
                }
                return new Blob([u8arr], { type: mime })
            }

            function downloadAndCompressFiles(fileList, outputName, callback, progressCb) {
                console.log('fileList', fileList);
                // 创建一个新的JSZip实例
                let zip = new JSZip();
                let fileNames = [];

                // 用于追踪已下载的文件数量和下载失败的文件数量
                let downloadedFiles = 0;
                let failedFiles = 0;

                // 遍历文件列表，下载并添加到压缩包中
                fileList.forEach(function (item, index) {
                    fetch(item.url)
                        .then(function (response) {
                            if (!response.ok) {
                                throw new Error('Download failed');
                            }
                            return response.blob();
                        })
                        .then(function (blob) {

                            let fileName = item.name;

                            // 重名文件，添加序号
                            if (fileNames.includes(fileName)) {
                                let count = 1;
                                let baseName = fileName.replace(/\.[^/.]+$/, ''); // Remove extension from filename
                                let extension = fileName.split('.').pop(); // Get the extension of the file

                                while (fileNames.includes(fileName)) {
                                    fileName = baseName + '(' + count + ').' + extension;
                                    count++;
                                }
                            }
                            // 将文件数据添加到压缩包中
                            zip.file(fileName, blob);
                            fileNames.push(fileName);

                            // 更新已下载的文件数量
                            downloadedFiles++;

                            progressCb({
                                total: fileList.length,
                                failedCount: failedFiles,
                                successCount: downloadedFiles,
                            })

                            // 检查是否所有文件都已下载完成
                            if (downloadedFiles === fileList.length) {
                                // 检查是否有文件下载失败
                                if (failedFiles === 0) {
                                    // 生成压缩包
                                    zip.generateAsync({ type: 'blob' }).then(function (content) {
                                        // 确定保存的文件名
                                        let saveFileName;
                                        if (outputName) {
                                            saveFileName = outputName.endsWith('.zip') ? outputName : outputName + '.zip';
                                        } else {
                                            saveFileName = 'download.zip';
                                        }

                                        // 使用file-saver库保存压缩包
                                        saveAs(content, saveFileName);

                                        // 调用回调函数，传递下载成功的文件数量
                                        if (callback) {
                                            callback(downloadedFiles);
                                        }
                                    });
                                } else {
                                    // 调用回调函数，传递下载成功的文件数量和下载失败的文件数量
                                    if (callback) {
                                        callback(downloadedFiles, failedFiles);
                                    }
                                }
                            }

                        })
                        .catch(function () {
                            // 更新下载失败的文件数量
                            failedFiles++;

                            // 检查是否所有文件都已下载完成
                            if (downloadedFiles + failedFiles === fileList.length) {
                                // 调用回调函数，传递下载成功的文件数量和下载失败的文件数量
                                if (callback) {
                                    callback(downloadedFiles, failedFiles);
                                }
                            }
                        });
                });
            }
        });
    </script>
</body>

</html>